<?php

namespace app\common\service;


use app\common\exception\ApiException;
use think\Loader;
use think\Log;

Loader::import('WxPay.WxPay', EXTEND_PATH, '.Api.php');

class Order {
    protected $openid;
    protected $order_id;

    public function __construct($order_id, $openid) {
        $this->openid   = $openid;
        $this->order_id = $order_id;
    }

    public static function makeOrderNo() {
        $yCode   = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
        $orderSn = $yCode[intval(date('Y')) - 2018] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
        return $orderSn;
    }

    public function getWxPrepay($order) {
        $wxOrderData = new \WxPayUnifiedOrder();
        $wxOrderData->SetOut_trade_no($order['order_no']);
        $wxOrderData->SetTrade_type('JSAPI');
        $wxOrderData->SetTotal_fee($order['total_price'] * 100);
        $wxOrderData->SetBody('锡盟微资讯广告位');
        $wxOrderData->SetOpenid($this->openid);
        $wxOrderData->SetNotify_url(config('wx.notice'));

        $wxOrder = \WxPayApi::unifiedOrder($wxOrderData);
        if ($wxOrder['return_code'] != 'SUCCESS' || $wxOrder['result_code'] != 'SUCCESS') {
            Log::record($wxOrder, 'error');
            Log::record('获取预支付订单失败', 'error');
            throw new ApiException($wxOrder, 200, 1);
        }
        model('Order')->where(['id' => $this->order_id])->update(['prepay_id' => $wxOrder['prepay_id']]);
        $signature = $this->sign($wxOrder);
        return $signature;
    }

    public function sign($wxOrder) {
        $jsApiPayData = new \WxPayJsApiPay();
        $jsApiPayData->SetAppid(config('wx.app_id'));
        //时间戳必须为string
        $jsApiPayData->SetTimeStamp((string)time());
        $rand = md5(time() . mt_rand(0, 1000));
        $jsApiPayData->SetNonceStr($rand);
        $jsApiPayData->SetPackage('prepay_id=' . $wxOrder['prepay_id']);
        $jsApiPayData->SetSignType('md5');
        $sign                 = $jsApiPayData->MakeSign();
        $rawValues            = $jsApiPayData->GetValues();
        $rawValues['paySign'] = $sign;
        unset($rawValues['appId']);
        return $rawValues;
    }
}